package com.woniuxy.secondkill.controller;

import com.woniuxy.secondkill.productor.KillProductor;
import com.woniuxy.secondkill.utils.ResponseResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Author zhangyong
 * @Date 2021/8/13 0013上午 11:32
 */
@RestController
public class KillController {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private KillProductor killProductor;

    @GetMapping("/kill")
    public ResponseResult kill(String account){
        //随机参数请求测压
        //account = UUID.randomUUID().toString();
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);

        //1.判断库存
        //1.1读取库存
        Integer integer = (Integer) redisTemplate.opsForValue().get("num");
        if (integer <= 0){
            responseResult.setMessage("已经卖完了，下次再来");
            return responseResult;
        }
        //2.判断当前用户是否已经抢过
        if(redisTemplate.hasKey(account)){

            responseResult.setMessage("请勿重复抢购");
            return responseResult;
        }
        //3.既有库存又没抢过    才用productor发送消息
        killProductor.send(account);    //异步操作

        //消息发送出去之后，当前的这个请求已经结束

        responseResult.setMessage("排队中，请稍后");

        return responseResult;
    }
}
